package top.yokey.shopai.retreat.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.Vector;

import top.yokey.shopai.R;
import top.yokey.shopai.retreat.viewmodel.RetreatReturnVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ImageHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zcom.util.JsonUtil;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zsdk.data.GoodsData;
import top.yokey.shopai.zsdk.data.RetreatData;

@Route(path = ARoutePath.RETREAT_RETURN)
public class RetreatReturnActivity extends BaseActivity {

    private final AppCompatImageView[] picImageView = new AppCompatImageView[3];
    private final Vector<String> idVector = new Vector<>();
    private final Vector<String> contentVector = new Vector<>();
    @Autowired(name = Constant.DATA_JSON)
    String json;
    private Toolbar mainToolbar = null;
    private RelativeLayout goodsRelativeLayout = null;
    private AppCompatImageView goodsImageView = null;
    private AppCompatTextView goodsNameTextView = null;
    private AppCompatTextView goodsPriceTextView = null;
    private AppCompatTextView goodsSpecTextView = null;
    private AppCompatTextView goodsNumberTextView = null;
    private AppCompatSpinner reasonSpinner = null;
    private AppCompatEditText priceEditText = null;
    private AppCompatEditText numberEditText = null;
    private AppCompatEditText messageEditText = null;
    private AppCompatTextView submitTextView = null;
    private int position = 0;
    private String price = "";
    private String number = "";
    private RetreatData data = null;
    private RetreatReturnVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_retreat_return);
        mainToolbar = findViewById(R.id.mainToolbar);
        goodsRelativeLayout = findViewById(R.id.goodsRelativeLayout);
        goodsImageView = findViewById(R.id.goodsImageView);
        goodsNameTextView = findViewById(R.id.goodsNameTextView);
        goodsPriceTextView = findViewById(R.id.goodsPriceTextView);
        goodsSpecTextView = findViewById(R.id.goodsSpecTextView);
        goodsNumberTextView = findViewById(R.id.goodsNumberTextView);
        reasonSpinner = findViewById(R.id.reasonSpinner);
        priceEditText = findViewById(R.id.priceEditText);
        numberEditText = findViewById(R.id.numberEditText);
        messageEditText = findViewById(R.id.messageEditText);
        submitTextView = findViewById(R.id.submitTextView);
        picImageView[0] = findViewById(R.id.zeroImageView);
        picImageView[1] = findViewById(R.id.oneImageView);
        picImageView[2] = findViewById(R.id.twoImageView);

    }

    @Override
    public void initData() {

        if (VerifyUtil.isEmpty(json)) {
            ToastHelp.get().showDataError();
            onReturn(false);
            return;
        }
        position = 0;
        data = JsonUtil.json2Object(json, RetreatData.class);
        vm = getVM(RetreatReturnVM.class);
        setToolbar(mainToolbar, R.string.goodsReturn);
        observeKeyborad(R.id.mainLinearLayout);
        vm.form(data);

    }

    @Override
    public void initEvent() {

        reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                data.setReasonId(idVector.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        priceEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String temp = Objects.requireNonNull(priceEditText.getText()).toString();
                if (ConvertUtil.string2Double(price) < ConvertUtil.string2Double(temp)) {
                    priceEditText.setText(price);
                    priceEditText.setSelection(price.length());
                }
                data.setRefundAmount(temp);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        numberEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String temp = Objects.requireNonNull(numberEditText.getText()).toString();
                if (ConvertUtil.string2Double(number) < ConvertUtil.string2Double(temp)) {
                    numberEditText.setText(number);
                    numberEditText.setSelection(number.length());
                }
                data.setGoodsNum(temp);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        picImageView[0].setOnClickListener(view -> {
            position = 0;
            App.get().startAlbum(get(), 1);
        });

        picImageView[1].setOnClickListener(view -> {
            position = 1;
            App.get().startAlbum(get(), 1);
        });

        picImageView[2].setOnClickListener(view -> {
            position = 2;
            App.get().startAlbum(get(), 1);
        });

        submitTextView.setOnClickListener(view -> {
            String message = Objects.requireNonNull(messageEditText.getText()).toString();
            if (VerifyUtil.isEmpty(message)) {
                ToastHelp.get().show(R.string.pleaseInputRefundExplain);
                return;
            }
            data.setBuyerMessage(message);
            data.setRefundType("2");
            submitTextView.setEnabled(false);
            submitTextView.setText(R.string.handlerIng);
            hideKeyboard();
            vm.submit(data);
        });

    }

    @Override
    public void initObserve() {

        vm.getFormLiveData().observe(this, bean -> {
            goodsRelativeLayout.setOnClickListener(view -> App.get().startGoods(new GoodsData(bean.getGoods().getGoodsId())));
            ImageHelp.get().display(bean.getGoods().getGoodsImg360(), goodsImageView);
            goodsNameTextView.setText(bean.getGoods().getGoodsName());
            goodsPriceTextView.setText("￥");
            goodsPriceTextView.append(bean.getGoods().getGoodsPrice());
            goodsSpecTextView.setText(bean.getGoods().getGoodsSpec());
            goodsNumberTextView.setText("x");
            goodsNumberTextView.append(bean.getGoods().getGoodsNum());
            idVector.clear();
            contentVector.clear();
            for (int i = 0; i < bean.getReasonList().size(); i++) {
                if (i == 0) {
                    data.setReasonId(bean.getReasonList().get(i).getReasonId());
                }
                idVector.add(bean.getReasonList().get(i).getReasonId());
                contentVector.add(bean.getReasonList().get(i).getReasonInfo());
            }
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(get(), R.layout.spinner_simple, contentVector);
            arrayAdapter.setDropDownViewResource(R.layout.spinner_item_small);
            data.setReasonId(idVector.get(0));
            reasonSpinner.setAdapter(arrayAdapter);
            price = bean.getGoods().getGoodsPayPrice();
            number = bean.getGoods().getGoodsNum();
            priceEditText.setHint(String.format(getString(R.string.maxRefundPrice), price));
            numberEditText.setHint(String.format(getString(R.string.maxRefundNumber), number));
            data.setRefundAmount(price);
            data.setGoodsNum(number);
        });

        vm.getPicLiveData().observe(this, bean -> {
            switch (position) {
                case 0:
                    data.setRefundPic0(bean.getFileName());
                    ImageHelp.get().display(bean.getPic(), picImageView[0]);
                    break;
                case 1:
                    data.setRefundPic1(bean.getFileName());
                    ImageHelp.get().display(bean.getPic(), picImageView[1]);
                    break;
                case 2:
                    data.setRefundPic2(bean.getFileName());
                    ImageHelp.get().display(bean.getPic(), picImageView[2]);
                    break;
            }
        });

        vm.getSubmitLiveData().observe(this, string -> {
            LiveEventBus.get(Constant.DATA_REFRESH).post(true);
            ToastHelp.get().show(R.string.returnSuccess);
            onReturn(false);
        });

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                DialogHelp.get().query(get(), R.string.loadFailure, bean.getReason(), view -> onReturn(false), view -> vm.form(data));
            } else {
                submitTextView.setEnabled(true);
                submitTextView.setText(R.string.submit);
                ToastHelp.get().show(bean.getReason());
            }
        });

    }

    @Override
    public void onActivityResult(int req, int res, @Nullable Intent intent) {

        super.onActivityResult(req, res, intent);
        if (res == RESULT_OK && req == Constant.CODE_ALBUM && intent != null) {
            List<LocalMedia> list = PictureSelector.obtainMultipleResult(intent);
            vm.uploadPic(new File(list.get(0).getCompressPath()));
        }

    }

}
